import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
import routes from './routes'

/*import Mock from './mock' // 模拟数据
Mock.bootstrap();*/

// 全局使用
import axios from 'axios'

//配置axios的全局基本路径 t
axios.defaults.baseURL='http://localhost:8080'
//全局属性配置，在任意组件内可以使用this.$http获取axios对象
Vue.prototype.$http = axios

import 'font-awesome/css/font-awesome.min.css'

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

//NProgress.configure({ showSpinner: false });

const router = new VueRouter({
  routes
})

// 百度地图的引用
import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, {
    ak: 'oNGpO5kwMvTLDgTxdjbL33thd20aMkLa'
})

//  静态资源拦截器，路由拦截器：
router.beforeEach((to, from, next) => {
    // 访问登录或店铺入驻，清除已有的用户信息
    if (to.path == '/login' || to.path == '/shopRegister') {
        localStorage.removeItem('token');
        localStorage.removeItem('logininfo');
        next()
        return;
    }
    let logininfo = JSON.parse(localStorage.getItem('logininfo'));
    if (!logininfo) { // 没有登录信息，跳转到登录界面
        next({ path: '/login'})
    } else {
        next()
    }
})

// axios前置拦截器：让所有请求都携带token，位于axios下方
axios.interceptors.request.use(config=>{
    // 获取token
    let token =  localStorage.getItem("token");
    if(token){ // 如果token存在
        config.headers['token']=token; // 将token存入请求头中
    }
    return config;
},error => {
    Promise.reject(error);
})

// 后置拦截器：接收后端拦截器返回的信息，以便跳转页面  {success: false, message: "noLogin"}
axios.interceptors.response.use(config=>{
    let data = config.data; // 接收前端的信息
    /* 如果满足后端返回的拦截信息 */
    if(!data.success && "noLogin" === data.msg)
    {
        // 删除浏览器中的登录信息
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        // 跳转到登录界面
        router.push({ path: '/login' });
    }
    return config;
},error => {
    Promise.reject(error)
})

/*登录拦截器*/
/*router.beforeEach((to, from, next) => {
  //NProgress.start();
  if (to.path == '/login') {
    sessionStorage.removeItem('user');
  }
  let user = JSON.parse(sessionStorage.getItem('user'));
  if (!user && to.path != '/login') {
    next({ path: '/login' })
  } else {
    next()
  }
})*/

//router.afterEach(transition => {
//NProgress.done();
//});

new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')

